import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import './Login1.css'
import ajax from '../../api/ajax'
import { useDispatch } from 'react-redux';
import { userChange } from '../../redux/UserSlice/UserSlice';

export default function Login() {
    const dispatch = useDispatch();
    // 0：代表登录页面， 1：代表注册页面
    const [NumberText, setNumberText] = useState(0)
    const navigate = useNavigate()
    const LoginFormRef = useRef(null)
    const RegisterFormRef = useRef(null)
    const boxRef = useRef(null)

    let [time, setTime] = useState(10)
    const [getCodeText, setGetCodeText] = useState(false)
    // 用户登录
    const loginEvent = async function () {
        
        let user = {
            userID: LoginFormRef.current.userID.value,
            password: LoginFormRef.current.password.value
        }
        if (user.userID === '' || user.password === '' ) {
            Toast.show({
                icon: 'fail',
                content: '请输入完整信息',
            })
            return;
        }
        const result = await ajax.post('/account/login', {
            tel: user.userID,
            password: user.password
        })
        console.log('result.msg', result.msg);
        if (result.msg !== 'success') {
            Toast.show({
                icon: 'fail',
                content: result.msg,
            })
            return ;
        }
        dispatch(userChange(JSON.parse(result.data) ))
        localStorage.setItem('userToken', result.data)
        localStorage.setItem('Authorization','*')
        navigate('/')
    }
    // 注册
    const RegisterEvent = async function () {
        // 验证码正则
        // const autoCodeReg= /^\d{6}$/;
        const RegisterDate = {
            phone: RegisterFormRef.current.register_phone.value,
            autoCode: RegisterFormRef.current.register_autoCode.value,
            password1: RegisterFormRef.current.register_password1.value,
            password2: RegisterFormRef.current.register_password2.value,
        }
        if (RegisterDate.phone === '' || RegisterDate.autoCode === '' || RegisterDate.password1 === '' || RegisterDate.password2 === '') {
            Toast.show({
                icon: 'fail',
                content: '请输入完整信息',
            })
            return;
        } else if (RegisterDate.autoCode !== autoCodeJudge) {
            // 比较验证码是否匹配
            Toast.show({
                icon: 'fail',
                content: '验证码不匹配',
            })
            return;

        } else if (RegisterDate.password1 !== RegisterDate.password2) {
            Toast.show({
                icon: 'fail',
                content: '与上一次密码不匹配',
            })
            return;
        }
        const result = await ajax.post('/account/register', {
            tel: RegisterDate.phone,
            password: RegisterDate.password1,
        })
        if (result.msg === 'success') {
            alert('注册成功，跳转登录页面')
            setNumberText(0)
        }else{
            alert('注册失败 ' + result.msg)
        }


    }
    
    // 接受返回过来都验证码
    const [autoCodeJudge, setAutoCodeJudge]=useState('')
    // 发送验证码
    let timer  //节流
    const getAutoCode = async () => {

        const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/
        if (!phoneReg.test(RegisterFormRef.current.register_phone.value)) {
            Toast.show({
                content: '请输入正确的手机号',
            })
            return;
        } else {

            if (timer) {
                return ;
                // 节流作用
            }
            timer = setInterval(() => {
                // 发送请求
                setGetCodeText(true)
                setTime(time--)

                if (time <= -2) {
                    // console.log('time<0', time <= 0);
                    clearInterval(timer)
                    setGetCodeText(false)
                    setTime(10)
                }
            }, 1000)

            // 将js对象转化为json字符串
            // const x = JSON.stringify({
            //     phone: RegisterFormRef.current.register_phone.value
            // })
            
            // 发送请求
            const result = await ajax.post('/account/sendCode',{
                phoneNumber: RegisterFormRef.current.register_phone.value,
            })
            console.log('result.data', result.data);
            setAutoCodeJudge(result.data)

        }

    }
    // 防止第一次再useEffect中获取不到boxRef.current
    const target = useCallback(() => {
        boxRef.current.style.height = document.documentElement.clientHeight + 'px'
    }, [document.documentElement.clientHeight])
    useEffect(() => {
        target()
    }, [])
    return (
        <div className="box" ref={boxRef}>
            {
                NumberText === 0 ?
                    <div className="login" >
                        <div className="login_top">
                            <div>+</div>
                            <h2>欢迎来到印象记账</h2>
                        </div>
                        <div className="login_bottom">
                            <form ref={LoginFormRef}>
                                <input type="text" className="input" placeholder="输入账号" id='userID' />
                                <input type="Password" className="input" placeholder="输入密码" id='password' />
                            </form>
                            <p>
                                <input type="checkbox" />
                                <span>我已阅读详细资料.</span>
                                <a href="#">转入到详细计划</a>
                            </p>
                            <button onClick={() => loginEvent()}>登录</button>

                            <p className='threeText'>
                                <span className='other'>其他登录方式</span>
                            </p>
                            <div className='threeLogin'>
                                <i><img src='i1.png'></img><span onClick={() => { }}>支付宝</span></i>
                                <i><img src='i2.png'></img><span onClick={() => { }}>微信</span></i>
                            </div>
                            <p className='noLogin'>
                                <span>无账号?</span>
                                <a onClick={() => {
                                    setNumberText(1)
                                }
                                }>点击注册</a>
                            </p>
                        </div>
                    </div>
                    :
                    <div className="register">
                        <div className="register_top">
                            <div>+</div>
                            <h2>注册页面</h2>
                        </div>
                        <div className="register_bottom">
                            <form ref={RegisterFormRef}>
                                <input type="text" className="input" placeholder="输入电话或邮箱" id='register_phone' />
                                <div className='AutoCode'>
                                    <input type="text" className="input" placeholder="输入验证码" id='register_autoCode' />
                                    {
                                        getCodeText ? <span className='register_bottomGetAutoCode'>
                                            {time + 's'}</span>
                                            :
                                            <a className='register_bottomGetAutoCode' onClick={() => getAutoCode()} >
                                                获取验证码</a>
                                    }
                                </div>
                                <input type="Password" className="input" placeholder="输入密码" id='register_password1' />
                                <input type="Password" className="input" placeholder="重复输入密码" id='register_password2' />
                            </form>
                            <button onClick={() => RegisterEvent()}>注册账号</button>
                            <p>
                                <span>已有账号?</span>
                                <a onClick={() => {
                                    setNumberText(0)
                                }}>点击登录</a>
                            </p>
                        </div>
                    </div>
            }

        </div>

    )
}
